package com.project.common;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 捕获异步请求时抛出的异常
 * @author weimingsen
 */
@Component
public class ResolveException implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {
		
		String requestType = request.getHeader("X-Requested-With");
		
		if("XMLHttpRequest".equals(requestType)){//如果是ajax则直接输出，否则有web.xml配置的500管理
			response.setCharacterEncoding("UTF-8");
//			PrintWriter writer = null;
			ServletOutputStream sops = null;
			try {
				sops = response.getOutputStream();
				sops.print("system error");
				sops.flush();
//				writer = response.getWriter();
//				writer.write("system error");
				ex.printStackTrace();
//				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(sops!=null){
					try {
						sops.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		return null;

	}

}
